/**
 * date:2021/2/18
 * author:thgold
 * version:2.0
 * description:layuimini common
 */
layui.define(["jquery"], function (exports) {
    var $ = layui.$;
    var common = {
        //打开弹窗成功回调
        success: function (layero, index, obj) {
            var iframe = window['layui-layer-iframe' + index];
            iframe.initView(obj);  //子窗口需要实现的函数    
        },
        closeIframe(){
            parent.tableConfig.editFormIdx=0;
            var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
            parent.layer.close(index); //再执行关闭 
            // parent.layer.close(parent.tableConfig.editFormIdx);
        },
        refreshPframe(){
            parent.tableConfig.tableIdx.reload(parent.tableConfig.tableOptions);
        },
        refreshAndClose(){
            common.refreshPframe();
            common.closeIframe();
        },
        initTableView(tableConfig){
            layui.use(['form', 'table'], function () {
                var $ = layui.jquery,
                    form = layui.form,
                    table = layui.table;
                    tableConfig.table = table;
                tableConfig.tableIdx = table.render(tableConfig.tableOptions);
    
                // 监听搜索操作
                form.on('submit(data-search-btn)', function (data) {
                    var result = JSON.stringify(data.field);
                    //执行搜索重载
                    tableConfig.tableOptions.where.searchParams = result;
                    tableConfig.tableIdx.reload(tableConfig.tableOptions);
                    return false;
                });
    
                /**
                 * 表头toolbar监听事件
                 */
                table.on('toolbar(currentTableFilter)', function (obj) {
                    if (obj.event === 'add') {  // 监听添加操作
                        tableConfig.tableOptions.page.curr = 1;
                        tableConfig.editMode=0;
                        tableConfig.editFormIdx = layer.open({
                            title: '添加用户',
                            closeBtn: false,
                            type: 2,
                            shade: 0.2,
                            resize: false,
                            anim: -1,
                            isOutAnim: false,
                            // maxmin: true,
                            // shadeClose: true,
                            area: ['100%', '100%'],
                            content: tableConfig.addPageUrl,
                            success: function (layero, index) {
                                common.success(layero, index, obj);
                            }
                        });
                        console.log(tableConfig.editFormIdx);
                        $(window).on("resize", function () {
                            console.log(tableConfig.editFormIdx);
                            if (tableConfig.editFormIdx) {
                                layer.full(tableConfig.editFormIdx);
                            }
                        });
                    } else if (obj.event === 'delete') {  // 监听删除操作
                        //记录当前操作页码
                        tableConfig.tableOptions.page.curr = $(".layui-laypage-em").next().html();
                        var checkStatus = table.checkStatus('currentTableId')
                            , data = checkStatus.data;
                        // layer.alert(JSON.stringify(data));
                        let ids = data.map(function(value){
                            return value.id;
                        })
                        ids = ids.join(",");
                        console.log("ids:"+ids);
                        if(ids.length>0){
                            layer.confirm('真的删除行么', function (index) {
                                $.ajax({
                                    url: tableConfig.deleteOneToManyUrl,
                                    data: {ids:JSON.stringify(ids)},
                                    type: 'post',
                                    dataType: 'json',
                                    success: function (res) {
                                        console.log(res);
                                        if (res.code !== 0) {
                                            layer.msg(res.msg, function () {
                                            });
                                            layer.close(index);
                                        } else {
                                            tableConfig.tableIdx.reload(tableConfig.tableOptions);
                                        }
                                        layer.close(index);
                                    },
                                    error: function (res) {
                                        console.log(res);
                                        layer.close(index);
                                    }
                                });
                            }); 
                        }else{
                            layer.msg("你没有选择任何数据!");
                        }
                        
                    }
                });
    
                /**
                * 表行tool监听事件
                */
                table.on('tool(currentTableFilter)', function (obj) {
                    var data = obj.data;
                    localStorage.setItem("checkedUserId", data.id);
                    //记录当前操作页码
                    tableConfig.tableOptions.page.curr = $(".layui-laypage-em").next().html();
                    tableConfig.currRowObject = obj;
                    if (obj.event === 'edit') {
                        console.log("common.......127");
                        tableConfig.editMode = 1;
                        tableConfig.editFormIdx = layer.open({
                            title: '编辑用户',
                            closeBtn: false,
                            type: 2,
                            shade: 0.2,
                            resize: false,
                            anim: -1,
                            // maxmin: true,
                            // shadeClose: true,
                            area: ['100%', '100%'],
                            content: tableConfig.editPageUrl,
                            success: function (layero, index) {
                                common.success(layero, index, obj);
                            }
                        });
                        $(window).on("resize", function () {
                            console.log(tableConfig.editFormIdx);
                            if (tableConfig.editFormIdx) {
                                layer.full(tableConfig.editFormIdx);
                            }
                        });
                        return false;
                    } else if (obj.event === 'delete') {
                        layer.confirm('真的删除行么', function (index) {
                            $.ajax({
                                url: tableConfig.deleteOneUrl,
                                data: { id: data.id },
                                type: 'get',
                                dataType: 'json',
                                success: function (res) {
                                    console.log(res);
                                    if (res.code !== 0) {
                                        layer.msg(res.msg, function () {
                                        });
                                    } else {
                                        // obj.del();
                                        tableConfig.tableIdx.reload(tableConfig.tableOptions);
                                    }
                                    layer.close(index);
                                },
                                error: function (res) {
                                    console.log(res);
                                    layer.close(index);
                                }
                            });
                        });
                    }
                });
    
                //监听表格复选框选择
                table.on('checkbox(currentTableFilter)', function (obj) {
                    console.log(obj)
                });
    
            });
        },
        getPNodeChildren(pid,data){
            let isFind = false;
            let children = [];
            for(let i = 0;i<data.length;i++){
                if(data[i].id===pid){
                    children = data[i].children;
                    break;
                }
                if(data[i].children){
                    children = common.getPNodeChildren(pid,data[i].children);
                    if(children.length!==0){
                        break;
                    }
                }
            }
            return children;
        },
        getPNodeChildrenByTableIdx(pid,tableIdx){
            return common.getPNodeChildren(pid,tableIdx.options.data);
        },
        updatePNodeChildrenByTableIdx(obj,tableIdx,data){
            console.log(data);
            tableIdx.update(obj.data.id, data);
            if(obj.data.pid!=='0'){
                let pNodeChildren = common.getPNodeChildrenByTableIdx(obj.data.pid,tableIdx);
                pNodeChildren.sort(function(a,b){
                    return b.sort-a.sort;
                });
                tableIdx.refresh(obj.data.pid,pNodeChildren);
            }else{
                tableIdx.options.data.sort(function(a,b){
                    return b.sort - a.sort;
                });
                tableIdx.refresh(tableIdx.options.data);
            }

        },
        addNodeByPNode(pObj,data,tableIdx){
            if(!pObj.data.children){
                pObj.data.children=[];
            }
            pObj.data.children.push(data);
            let pNodeChildren = pObj.data.children;
            pNodeChildren.sort(function(a,b){
                return b.sort-a.sort;
            });
            tableIdx.refresh(pObj.data.id,pNodeChildren);
            pObj.tr.click();
        },
        addNodeByRoot(data,tableIdx){
            tableIdx.options.data.push(data);
            tableIdx.options.data.sort(function(a,b){
                return b.sort - a.sort;
            });
            tableIdx.refresh(tableIdx.options.data);
        },
        //得到一个节点下的所有子节点id
        getNodeAllIds(data){
            let ids = [];
            ids.push(data.id);
            if(data.children){
                for(let i = 0;i<data.children.length;i++){
                    let result = common.getNodeAllIds(data.children[i]);
                    for(let j = 0;j<result.length;j++){
                        ids.push(result[j]);
                    }
                }
            }
            return ids;
        },
        //树表格初始化，参数
        initTreeTableView(tableConfig){
            layui.use(['layer', 'util', 'treeTable','common'], function () {
                var $ = layui.jquery;
                var layer = layui.layer;
                var util = layui.util;
                var common = layui.common;
                var treeTable = layui.treeTable;
                // 渲染表格
                let topHeight = $('.table-search-fieldset').height()+80;
                console.log(topHeight);
                tableConfig.tableOptions.height = `full-${topHeight}`
                tableConfig.tableIdx = treeTable.render(tableConfig.tableOptions);
                // 工具列点击事件
                treeTable.on('tool(currentTableId)', function (obj) {
                    var event = obj.event;
                    var data = obj.data;
                    localStorage.setItem("checkedUserId",data.id);
                    tableConfig.currRowObject = obj;
                    if (event === 'delete') {
                        layer.msg('删除成功');
                        // let tr = obj.tr[0];
                        console.log(data);
                        let ids = common.getNodeAllIds(obj.data);
                        ids = ids.join(",");
                        console.log("ids:"+ids);
                        layer.confirm('真的删除行么', function (index) {
                            $.ajax({
                                url: tableConfig.deleteOneToManyUrl,
                                data: {ids:JSON.stringify(ids)},
                                type: 'post',
                                dataType: 'json',
                                success: function (res) {
                                    console.log(res);
                                    if (res.code !== 0) {
                                        layer.msg(res.msg, function () {
                                        });
                                        layer.close(index);
                                    } else {
                                        let pid = data.pid;
                                        tableConfig.tableIdx.del(obj.data.id);
                                        common.updatePNodeChildrenByTableIdx(obj,tableConfig.tableIdx);
                                    }
                                    layer.close(index);
                                },
                                error: function (res) {
                                    console.log(res);
                                    layer.close(index);
                                }
                            });
                        });    
                    } else if (event === 'edit') {
                        // layer.msg('修改成功');
                        // obj.update({ authorityName: '新的名称' });
                        tableConfig.editMode = 1;
                        tableConfig.editFormIdx = layer.open({
                            title: '编辑角色',
                            closeBtn: false,
                            type: 2,
                            shade: 0.2,
                            resize:false,
                            anim:-1,
                            // maxmin: true,
                            // shadeClose: true,
                            area: ['100%', '100%'],
                            content: tableConfig.editPageUrl,
                            success: function (layero, index) {
                                    common.success(layero, index, obj);
                                }
                        });
                        $(window).on("resize", function () {
                            console.log(tableConfig.editFormIdx);
                            if(tableConfig.editFormIdx){
                                layer.full(tableConfig.editFormIdx);
                            }
                        });
                    }else if(event === 'add'){
                        tableConfig.editMode = 2;
                        tableConfig.editFormIdx = layer.open({
                            title: '添加授权',
                            closeBtn: false,
                            type: 2,
                            shade: 0.2,
                            resize:false,
                            anim:-1,
                            // maxmin: true,
                            // shadeClose: true,
                            area: ['100%', '100%'],
                            content: tableConfig.addPageUrl,
                            success: function (layero, index) {
                                    common.success(layero, index, obj);
                                }
                        });
                        console.log(tableConfig.editFormIdx);
                        $(window).on("resize", function () {
                            console.log(tableConfig.editFormIdx);
                            if(tableConfig.editFormIdx){
                                layer.full(tableConfig.editFormIdx);
                            }
                        });
                    }
                });
                // 头部工具栏点击事件
                treeTable.on('toolbar(currentTableId)', function (obj) {
                    switch (obj.event) {
                        case 'add':
                        tableConfig.editMode = 0;
                        tableConfig.editFormIdx = layer.open({
                                title: '添加授权',
                                closeBtn: false,
                                type: 2,
                                shade: 0.2,
                                resize:false,
                                anim:-1,
                                // maxmin: true,
                                // shadeClose: true,
                                area: ['100%', '100%'],
                                content: tableConfig.addPageUrl,
                                success: function (layero, index) {
                                    common.success(layero, index, obj);
                                }
                            });
                            console.log(tableConfig.editFormIdx);
                            $(window).on("resize", function () {
                                console.log(tableConfig.editFormIdx);
                                if(tableConfig.editFormIdx){
                                    layer.full(tableConfig.editFormIdx);
                                }
                            });
                            break;
                        case 'delete':
                            layer.msg('删除');
                            break;
                        case 'update':
                            layer.msg('编辑');
                            break;
                        case 'LAYTABLE_TIPS':
                            layer.msg('提示');
                            break;
                        case 'expandAll':
                            layer.msg('全部展开');
                            tableConfig.tableIdx.expandAll();
                            break;
                        case 'foldAll':
                            layer.msg('全部折叠');
                            tableConfig.tableIdx.foldAll();
                            break;
                        case 'LAYTABLE_REFRESH':
                            tableConfig.tableIdx.reload();
                            break;
                    }
                });
                treeTable.on('checkbox(currentTableId)', function(obj){
                    console.log(obj.checked);  // 当前是否选中状态
                    console.log(obj.data);  // 选中行的相关数据
                    console.log(obj.type);  // 如果触发的是全选，则为：all，如果触发的是单选，则为：one
                });
                // 监听行单击事件
                treeTable.on('row(currentTableId)', function(obj){
                    // console.log(obj.tr) //得到当前行元素对象
                    console.log(obj.data) //得到当前行数据
                    tableConfig.currRowPObject = obj;
                    if(obj.data.children&&obj.data.children.length===0){
                        obj.data.haveChild=false;
                        obj.update(obj.data);
                    }else if(obj.data.children&&obj.data.children.length>0){
                        obj.data.haveChild=true;
                        obj.update(obj.data);
                    }
                });
    
            });
        },
        initTreeTableView_bk(tableConfig){
            layui.use(['layer', 'util', 'treeTable','common'], function () {
                var $ = layui.jquery;
                var layer = layui.layer;
                var util = layui.util;
                var common = layui.common;
                var treeTable = layui.treeTable;
                // 渲染表格
                let topHeight = $('.table-search-fieldset').height()+80;
                console.log(topHeight);
                tableConfig.tableOptions.height = `full-${topHeight}`
                tableConfig.tableIdx = treeTable.render(tableConfig.tableOptions);
                // 工具列点击事件
                treeTable.on('tool(currentTableId)', function (obj) {
                    var event = obj.event;
                    var data = obj.data;
                    localStorage.setItem("checkedUserId",data.id);
                    tableConfig.currRowObject = obj;
                    //记录父节点
                    clickPobj($,obj);
                    if (event === 'delete') {
                        layer.msg('删除成功');
                        // let tr = obj.tr[0];
                        console.log(data);
                        let ids = getIds(data);
                        console.log("ids:"+ids);
                        layer.confirm('真的删除行么', function (index) {
                            $.ajax({
                                url: tableConfig.deleteOneToManyUrl,
                                data: {ids:JSON.stringify(ids)},
                                type: 'post',
                                dataType: 'json',
                                success: function (res) {
                                    console.log(res);
                                    if (res.code !== 0) {
                                        layer.msg(res.msg, function () {
                                        });
                                        layer.close(index);
                                    } else {
                                        let pid = data.pid;
                                        obj.del();
                                        clickPobj($,obj);
                                    }
                                    layer.close(index);
                                },
                                error: function (res) {
                                    console.log(res);
                                    layer.close(index);
                                }
                            });
                        });    
                    } else if (event === 'edit') {
                        // layer.msg('修改成功');
                        // obj.update({ authorityName: '新的名称' });
                        tableConfig.editMode = 1;
                        tableConfig.editFormIdx = layer.open({
                            title: '编辑角色',
                            closeBtn: false,
                            type: 2,
                            shade: 0.2,
                            resize:false,
                            anim:-1,
                            // maxmin: true,
                            // shadeClose: true,
                            area: ['100%', '100%'],
                            content: tableConfig.editPageUrl,
                            success: function (layero, index) {
                                    common.success(layero, index, obj);
                                }
                        });
                        $(window).on("resize", function () {
                            console.log(tableConfig.editFormIdx);
                            if(tableConfig.editFormIdx){
                                layer.full(tableConfig.editFormIdx);
                            }
                        });
                    }else if(event === 'add'){
                        tableConfig.editMode = 2;
                        tableConfig.editFormIdx = layer.open({
                            title: '添加授权',
                            closeBtn: false,
                            type: 2,
                            shade: 0.2,
                            resize:false,
                            anim:-1,
                            // maxmin: true,
                            // shadeClose: true,
                            area: ['100%', '100%'],
                            content: tableConfig.addPageUrl,
                            success: function (layero, index) {
                                    common.success(layero, index, obj);
                                }
                        });
                        console.log(tableConfig.editFormIdx);
                        $(window).on("resize", function () {
                            console.log(tableConfig.editFormIdx);
                            if(tableConfig.editFormIdx){
                                layer.full(tableConfig.editFormIdx);
                            }
                        });
                    }
                });
                // 头部工具栏点击事件
                treeTable.on('toolbar(currentTableId)', function (obj) {
                    switch (obj.event) {
                        case 'add':
                        tableConfig.editMode = 0;
                        tableConfig.editFormIdx = layer.open({
                                title: '添加授权',
                                closeBtn: false,
                                type: 2,
                                shade: 0.2,
                                resize:false,
                                anim:-1,
                                // maxmin: true,
                                // shadeClose: true,
                                area: ['100%', '100%'],
                                content: tableConfig.addPageUrl,
                                success: function (layero, index) {
                                    common.success(layero, index, obj);
                                }
                            });
                            console.log(tableConfig.editFormIdx);
                            $(window).on("resize", function () {
                                console.log(tableConfig.editFormIdx);
                                if(tableConfig.editFormIdx){
                                    layer.full(tableConfig.editFormIdx);
                                }
                            });
                            break;
                        case 'delete':
                            layer.msg('删除');
                            break;
                        case 'update':
                            layer.msg('编辑');
                            break;
                        case 'LAYTABLE_TIPS':
                            layer.msg('提示');
                            break;
                        case 'expandAll':
                            layer.msg('全部展开');
                            tableConfig.tableIdx.expandAll();
                            break;
                        case 'foldAll':
                            layer.msg('全部折叠');
                            tableConfig.tableIdx.foldAll();
                            break;
                        case 'LAYTABLE_REFRESH':
                            tableConfig.tableIdx.reload();
                            break;
                    }
                });
                treeTable.on('checkbox(currentTableId)', function(obj){
                    console.log(obj.checked);  // 当前是否选中状态
                    console.log(obj.data);  // 选中行的相关数据
                    console.log(obj.type);  // 如果触发的是全选，则为：all，如果触发的是单选，则为：one
                });
                // 监听行单击事件
                treeTable.on('row(currentTableId)', function(obj){
                    // console.log(obj.tr) //得到当前行元素对象
                    console.log(obj.data) //得到当前行数据
                    tableConfig.currRowPObject = obj;
                    if(obj.data.children&&obj.data.children.length===0){
                        obj.data.haveChild=false;
                        obj.update(obj.data);
                    }else if(obj.data.children&&obj.data.children.length>0){
                        obj.data.haveChild=true;
                        obj.update(obj.data);
                    }
                });
    
            });
        }
    };

    exports("common", common);
});